<template>
  <div>
    <el-upload
      class="upload"
      drag
      action="#"
      :show-file-list="false"
      :http-request="uploadFile"
      :before-upload="beforeUpload"
    >
      <img alt="上传失败"
        v-if="this.$props.successImageSrc"
        :src="this.$props.successImageSrc"
        class="upload-image"
      />
      <div v-else>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </div>
      <div class="el-upload__tip" slot="tip">{{this.$props.uploadTip}}</div>
      <!-- 进度条 -->
      <el-progress
        v-if="progress > 0"
        type="line"
        :percentage="progress"
        style="margin-bottom: 20px"
      ></el-progress>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: {
    // 上传进度
    progress: {
      type: Number,
      default: 0
    },
    // 支持的格式，例如：["image/png"]
    supportFormats: {
      type: Array,
      required: true
    },
    // 大小限制,单位是MB
    maxSize: {
      type: Number,
      required: true
    },
    // 上传提示语
    uploadTip: {
      type: String,
      default: ""
    },
    // 上传成功显示的图片 url
    successImageSrc: {
      type: String,
      default: null
    },

    
  },

  data() {
    return {
    };
  },
  methods: {
    //上传文件
    uploadFile(val) {
      this.$emit("uploadFile", val.file);
    },

    //格式和大小验证
    beforeUpload(file) {
      // console.log(file.type);
      const { supportFormats, maxSize } = this.$props;
      const isFormatOk = supportFormats.includes(file.type);
      const isLtSize = file.size < maxSize * 1024 * 1024;
      if (!isFormatOk) {
        this.$message.error("文件格式错误！");
        return false;
      }
      if (!isLtSize) {
        this.$message.error("文件大小超出范围！");
        return false;
      }
    },
  }
};
</script>
<style scoped>
.upload-image {
    height: 178px;
    width: auto;
}
</style>